package com.hzh.flink.core

import org.apache.flink.api.common.functions.{RichMapFunction, RuntimeContext}
import org.apache.flink.api.common.state.{ValueState, ValueStateDescriptor}
import org.apache.flink.configuration.Configuration
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._

object Demo13ValueState {
  def main(args: Array[String]): Unit = {
    //创建环境
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
    env.setParallelism(1)

    /**
     *
     * 打开checkPoint
     *
     */

    // 每 1000ms 开始一次 checkpoint
    env.enableCheckpointing(5000)

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 允许两个连续的 checkpoint 错误
    env.getCheckpointConfig.setTolerableCheckpointFailureNumber(2)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    // 使用 externalized checkpoints，这样 checkpoint 在作业取消后仍就会被保留
    env.getCheckpointConfig.setExternalizedCheckpointCleanup(
      ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)

    /**
     * 设置checkPoint的保存位置
     *
     * checkPoint超时会失败
     *
     */

    env.setStateBackend(new HashMapStateBackend())
    //将状态保存到hdfs
    env.getCheckpointConfig.setCheckpointStorage("hdfs://master:9000/flink/checkpoint")

    /**
     * 读取socket的数据
     */
    val lines: DataStream[String] = env.socketTextStream("master", 8888)

    val keyByDS: KeyedStream[String, String] = lines.flatMap(_.split(","))
      .keyBy(word => word)

    val countDS: DataStream[(String, Int)] = keyByDS.map(new RichMapFunction[String, (String, Int)]() {


      /**
       * ValueState:单值状态，为每一个key在状态中保存一个值
       *
       */
      var valueState: ValueState[Int] = _


      /**
       * open:在map之前执行，每一个task中只执行一次
       * flink的状态需要在open中定义
       * 状态：用于保存之前结果的变量，和普通的区别，状态会被checkpoint持久化到hdfs中
       *
       */
      override def open(parameters: Configuration): Unit = {
        //获取context上下文对象
        //getRuntimeContext是AbstractRichFunction中的一个方法
        val context: RuntimeContext = getRuntimeContext
        //创建状态的描述对象
        val valueStateDesc = new ValueStateDescriptor[Int]("count", classOf[Int])

        valueState = context.getState(valueStateDesc)

      }

      override def map(value: String): (String, Int) = {

        //1、获取状态中保存的数据
        var count: Int = valueState.value()

        //2、累加
        count += 1

        //3、更新状态

        valueState.update(count)

        //返回单词数量

        (value, count)

      }
    })

    countDS.print()

    env.execute()


  }

}
